package ferp.android.tasks.center;

import android.content.Context;
import android.os.AsyncTask;
import ferp.android.managers.ProfileManager;
import ferp.center.client.Action;
import ferp.center.network.request.RequestProfileDelete;
import ferp.center.network.response.ResponseProfileDelete;
import ferp.core.log.Log;
import ferp.core.player.Profile;

/**
 * User: igorgok
 * Date: 5/21/12 10:48 AM
 */
public class TaskProfileDelete extends AsyncTask<Void, Void, Void>
{
  public interface Listener
  {
    void onBeforeProfileDeletion();
    void onAfterProfileDeletion();
  }

  public TaskProfileDelete(Context context, Profile profile, TaskProfileDelete.Listener listener)
  {
    this.pm = ProfileManager.regular(context);

    this.profile = profile;
    this.listener = listener;
  }

  @Override
  protected void onPreExecute()
  {
    listener.onBeforeProfileDeletion();
  }

  @Override
  protected Void doInBackground(Void... voids)
  {
    try
    {
      // delete local profile
      pm.deleteProfile(profile, true);

      // do not look in the preferences for center access permission
      if (profile.centerId != 0)
      {
        RequestProfileDelete request = new RequestProfileDelete();

        request.id = profile.centerId;

        Action.execute(Action.PROFILE_DELETE, request, ResponseProfileDelete.class);
      }
    }
    catch (Exception e)
    {
      Log.error(Action.TAG, e);
    }

    return null;
  }

  @Override
  protected void onPostExecute(Void aVoid)
  {
    listener.onAfterProfileDeletion();
  }

  private ProfileManager pm;
  private final Profile profile;
  private final TaskProfileDelete.Listener listener;
}
